package com.augurit.common.system.service.org.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;

import com.augurit.common.base.form.ResultForm;
import com.augurit.common.constant.OrgConstant;
import com.augurit.common.dao.AcUserFuncDao;
import com.augurit.common.dao.AcUserRoleDao;
import com.augurit.common.dao.AcUserShortcutDao;
import com.augurit.common.dao.OmOrgAdminDao;
import com.augurit.common.dao.OmOrgDao;
import com.augurit.common.dao.OmUserDao;
import com.augurit.common.dao.OmUserGroupDao;
import com.augurit.common.dao.OmUserOrgDao;
import com.augurit.common.dao.OmUserPositionDao;
import com.augurit.common.entity.OmOrg;
import com.augurit.common.entity.OmUser;
import com.augurit.common.entity.OmUserOrg;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.system.convert.OmOrgConverter;
import com.augurit.common.system.convert.OmUserConverter;
import com.augurit.common.system.convert.OmUserGroupConverter;
import com.augurit.common.system.convert.OmUserOrgConverter;
import com.augurit.common.system.convert.OmUserPositionConverter;
import com.augurit.common.system.service.org.IOmPositionService;
import com.augurit.common.system.service.org.IOmUserService;
import com.augurit.common.system.util.MsgUtils;
import com.augurit.common.system.util.OrgUtils;
import com.augurit.common.system.web.org.form.OmOrgForm;
import com.augurit.common.system.web.org.form.OmPositionForm;
import com.augurit.common.system.web.org.form.OmUserForm;
import com.augurit.common.system.web.org.form.OmUserGroupForm;
import com.augurit.common.system.web.org.form.OmUserOrgForm;
import com.augurit.common.system.web.org.form.OmUserPositionForm;
import com.augurit.common.util.HqlUtils;
import com.augurit.common.util.PageUtils;
import com.augurit.common.util.lang.ArrayUtils;
import com.augurit.common.util.lang.CollectionUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.sendNotice.service.IUserForFxService;

/**
 * 用户逻辑实现类
 */
@Service
@Transactional
public class OmUserServiceImpl implements IOmUserService {
	
	// DAO 引用
	@Autowired
	private OmUserDao omUserDao;
	
	@Autowired
	private OmOrgAdminDao omOrgAdminDao;	//机构管理权限用户关联表对应的DAO类
	
	@Autowired
	private OmUserOrgDao omUserOrgDao;		//机构用户关联表对应的DAO类
	
	@Autowired
	private OmUserGroupDao omUserGroupDao;	//工作组用户关联表对应的DAO类
	
	@Autowired
	private OmUserPositionDao omUserPositionDao;	//用户岗位关联表对应的dao
	
	@Autowired
	private AcUserRoleDao userRoleDao;
	
	@Autowired
	private AcUserFuncDao userFuncDao;
	
	@Autowired
	private AcUserShortcutDao userShortcutDao;
	
	@Autowired
	private OmOrgDao omOrgDao;
	
	@Autowired
	private IOmPositionService omPositionService;

	@Autowired
	private ISysCodeService sysCodeService;
	
	@Autowired
	private IUserForFxService userForFxService;
	
	
	/**
	 * 根据用户主键获取用户Form对象
	 * @param id  用户主键
	 * @return 用户Form对象
	 */
	@Transactional(readOnly = true)
	public OmUserForm get(Long id){
		OmUserForm form = omUserDao.getForm(id);
		return form;
	}

	/**
	 * 保存用户Form对象数组
	 * @param forms 用户Form对象或对象数组
	 */
	public void save(OmUserForm... forms){
		if(forms != null)
			for(OmUserForm form : forms)
				omUserDao.save(form);
	}

	/**
	 * 根据主键ID集合删除多个用户对象
	 * @param ids 用户主键集合
	 */
	public void delete(Long... ids) {
		if(ids != null)
			omUserDao.delete(ids);
	}

	
	
	/**
	 * 获取用户基本信息
	 * @param loginName 用户登录名
	 * @return
	 */
	@Transactional(readOnly = true)
	public OmUserForm get(String loginName) {
		return omUserDao.getForm(loginName);
	}

	/**
	 * 检验登录用户的用户名和密码是否正确
	 * @param loginName 用户登录名
	 * @param password 用户密码
	 * @return
	 */
	@Transactional(readOnly = true)
	public boolean isValid(String loginName, String password){
		return omUserDao.isValid(loginName, password);
	}
	
	/**
	 * 根据登录用户的用户名和密码获取用户对象
	 * @param loginName 用户登录名
	 * @param password 用户密码
	 * @return 如用户名和密码正确则返回用户对象，否则返回NULL
	 */
	@Transactional(readOnly = true)
	public OmUserForm getValidUser(String loginName, String password){
		return omUserDao.getValidUser(loginName, password);
	}
	
	/**
	 * 根据主键id删除本用户节点以及关联的机构，岗位，工作组
	 * @param userId 用户节点主键
	 */
	public void deleteUserCascade(Long userId){
		// 删除用户关联的机构
		omOrgAdminDao.deleteByUserId(userId);
		omUserOrgDao.deleteByUserId(userId);
		
		// 删除用户关联的岗位
		omUserPositionDao.deleteByUserId(userId);
		
		// TODO 删除用户关联的工作组
		omUserGroupDao.deleteByUserId(userId);
		
		//TODO 删除用户关联的角色
		this.disAssociationRolebyUserId(userId);
		
		//TODO 删除用户关联的功能
		this.disAssociationFunbyUserId(userId);
		
		//TODO 删除用户关联的快捷键
		this.disAssociationShortcutByUserId(userId);
		
		// 删除本用户
		omUserDao.delete(userId);
	}
	
	
	
	
	/**
	 * 删除用户与机构的关联，不删除用户本身
	 * @param userId 用户主键
	 * @param orgId  机构主键
	 */
	public void deleteUserFromOrg(Long userId, Long orgId,boolean flag){
		if(userId != null && orgId != null){
			//删除用户在该机构下的岗位
			omPositionService.deleteUserPosOfCurOrg(userId, orgId);
			
			// 删除用户与该机构的关联
			omOrgAdminDao.deleteByUserIdAndOrgId(userId, orgId);
			omUserOrgDao.deleteUserFromOrg(userId, orgId);
			
			List<OmUserOrg> entities = omUserOrgDao.getByUserId(userId);
			//如果用户不属于一个机构
			if(entities == null || entities.size() == 0){
				
				// 删除用户关联的岗位
				omUserPositionDao.deleteByUserId(userId);
				
				// TODO 删除用户关联的工作组
				omUserGroupDao.deleteByUserId(userId);
				
				//TODO 删除用户关联的角色
				this.disAssociationRolebyUserId(userId);
				
				//TODO 删除用户关联的功能
				this.disAssociationFunbyUserId(userId);
				
				//TODO 删除用户关联的快捷键
				this.disAssociationShortcutByUserId(userId);
				if(flag){
					userForFxService.deleteUser(userId);
				}
				// 删除本用户
				omUserDao.delete(userId);
								
			}
		}
		
	}
	
	/**
	 * 删除用户与岗位的关联，不删除用户本身
	 * @param userId 用户主键
	 * @param posId 岗位主键
	 */
	public void deleteUserFromPos(Long userId, Long posId){
		// 删除用户关联的岗位
		if(userId != null && posId != null){
			omUserPositionDao.deleteUserFromPos(userId, posId);
		}
	}
	
	/**
	 * 删除用户与工作组的关联，不删除用户本身
	 * @param userId 用户主键
	 * @param groupId 工作组主键
	 */
	public void deleteUserFromGroup(Long userId, Long groupId){
		// TODO 删除用户关联的工作组
		if(userId != null && groupId != null){
			//删除用户在该工作组下的岗位
			omPositionService.deleteUserPosOfCurGroup(userId, groupId);
			
			omUserGroupDao.deleteUserFromGroup(userId, groupId);
		}
	}
	
	/**
	 * 获取指定用户的分页查询
	 * @param page
	 * @param form
	 * @param userIds 用户id数组 
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> getUsersInUserIds(Page<OmUserForm> page, OmUserForm form, Long[] userIds){
		if(userIds != null && userIds.length > 0){
			Page pg = PageUtils.newPageInstance(page);
			
			StringBuffer hql = new StringBuffer("from OmUser ps where ");
			hql.append(HqlUtils.buildOrCondition("ps", "userId", userIds));
			List values = new ArrayList();
			
			if(form != null){
				
				if(StringUtils.isNotBlank(form.getLoginName())){
					hql.append(" and ps.loginName like ? ");
					values.add("%" + form.getLoginName() + "%");
				}
				
				if(StringUtils.isNotBlank(form.getUserCode())){
					hql.append(" and ps.userCode like ? ");
					values.add("%" + form.getUserCode() + "%");
				}
				
				if(StringUtils.isNotBlank(form.getUserName())){
					hql.append(" and ps.userName like ? ");
					values.add("%" + form.getUserName() + "%");
				}
				
				if(StringUtils.isNotBlank(form.getPosition())){
					hql.append(" and ps.position = ?");
					values.add(form.getPosition());
				}
				
				if(StringUtils.isNotBlank(form.getIsActive())){
					hql.append(" and ps.isActive = ?");
					values.add(form.getIsActive());
				}
			}

			//排序
			hql.append(HqlUtils.buildOrderBy(page, "ps"));

			omUserDao.findPage(pg, hql.toString(), values);
			
			List<OmUserForm> list = OmUserConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
			return page;
		}
		return null;
	}
	
	
	/**
	 * 给定用户id数组，获取不在id数组中的分页查询
	 * @author 王剑文
	 * @param page
	 * @param form
	 * @param userIds
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> getUsersNotInUserIds(Page<OmUserForm> page, OmUserForm form, Long[] userIds){
		if(userIds != null && userIds.length > 0){
			Page pg = PageUtils.newPageInstance(page);
			
			StringBuffer hql = new StringBuffer("from OmUser ps where ");
			hql.append(HqlUtils.buildAndCondition("ps", "userId", userIds));
			List values = new ArrayList();
			
			if(form != null){
				if(StringUtils.isNotBlank(form.getUserCode())){
					hql.append(" and ps.userCode like ? ");
					values.add("%" + form.getUserCode() + "%");
				}
				
				if(StringUtils.isNotBlank(form.getUserName())){
					hql.append(" and ps.userName like ? ");
					values.add("%" + form.getUserName() + "%");
				}
			}

			//排序
			hql.append(HqlUtils.buildOrderBy(page, "ps"));
			
			omUserDao.findPage(pg, hql.toString(), values);
			
			List<OmUserForm> list = OmUserConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
			return page;
			
		}
		return null;
	}

	/**
	 * 根据机构主键posId获取关联用户集合
	 * @return 用户集合
	 */
	@Transactional(readOnly = true)
	public List<OmUserForm> getUsersByPosId(Long posId) {
		return omUserDao.getUsersByPosId(posId);
	}
	
	
	/**
	 * 根据机构主键orgId分页查询关联用户集合
	 * @param orgId 机构主键
	 * @param page 分页对象
	 * @return 分页的用户集合
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> getUsersByPosId(Long posId, Page<OmUserForm> page) {
		if(posId != null){
			//建立分页对象
			Page<OmUser> pg = PageUtils.newPageInstance(page);
			
			//按分页条件查询
			String hql = OmUserDao.HQL_GET_USERS_BY_POS_ID;
			List values = new ArrayList();
			values.add(posId);
			
			pg = omUserDao.findPage(pg,hql,values);
			
			// 转换为Form对象列表并赋值到原分页对象中
			List<OmUserForm> list = OmUserConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
		}
		return page;
	}
	
	/**
	 * 根据机构主键orgId获取关联用户集合
	 * @return 用户集合
	 */
	@Transactional(readOnly = true)
	public List<OmUserForm> getUsers(Long orgId) {
		return omUserDao.getUsersByOrgId(orgId);
	}

	/**
	 * 根据机构主键orgId分页查询关联用户集合
	 * @param orgId 机构主键
	 * @param page 分页对象
	 * @return 分页的用户集合
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> getUsers(Long orgId, Page<OmUserForm> page) {
		if(orgId != null){
			//建立分页对象
			Page<OmUser> pg = PageUtils.newPageInstance(page);
			
			//按分页条件查询
			String hql = OmUserDao.HQL_GET_USERS_BY_ORG_ID;
			List values = new ArrayList();
			values.add(orgId);
			pg = omUserDao.findPage(pg, hql, values);
			
			// 转换为Form对象列表并赋值到原分页对象中
			List<OmUserForm> list = OmUserConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
		}
		return page;
	}
	
	/**
	 * 根据工作组主键groupId分页查询关联用户集合
	 * @param groupId 工作组主键
	 * @param page 分页对象
	 * @return 分页的用户集合
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> getUsersByGroup(Long groupId, Page<OmUserForm> page) {
		if(groupId != null){
			//建立分页对象
			Page<OmUser> pg = PageUtils.newPageInstance(page);
			
			//按分页条件查询
			String hql = OmUserDao.HQL_GET_USERS_BY_GROUP_ID;
			List values = new ArrayList();
			values.add(groupId);
			pg = omUserDao.findPage(pg, hql, values);
			
			// 转换为Form对象列表并赋值到原分页对象中
			List<OmUserForm> list = OmUserConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
		}
		return page;
	}
	
	/**
	 * 移动用户到另一岗位
	 * @param  userId 用户主键
	 * @param oldPosId 用户原来所在的岗位
	 * @param targetPosId 要移动到的岗位主键
	 */
	public void moveUserToPosition(Long userId, Long oldPosId, Long targetPosId){
		if(userId != null && targetPosId != null){
			if(oldPosId != null)
				omUserPositionDao.moveUserToOtherPosition(userId, oldPosId, targetPosId);
			else
				omUserPositionDao.moveUserToPosition(userId, targetPosId);
		}
	}
	
	/**
	 * 移动用户到另一机构
	 * @param  userId 用户主键
	 * @param oldOrgId 用户原来所在的机构主键
	 * @param targetOrgId 要移动到的机构主键
	 */
	public void moveUserToOrg(Long userId, Long oldOrgId,Long targetOrgId){
		if(userId != null && oldOrgId != null &&targetOrgId != null){
			omUserOrgDao.moveUserToOtherOrg(userId, oldOrgId, targetOrgId);
		}
	}
	
	/**
	 * 判断该用户是否是系统管理员
	 * @param userId 用户主键
	 * @return 如果用户是超级管理员，返回true;否则，返回false
	 */
	@Transactional(readOnly = true)
	public boolean isSystemAdmin(Long userId){
		return omUserDao.isSystemAdmin(userId);
	}
	
	/**
	 * 在机构下新增用户
	 * @param form 用户对象
	 * @param orgId 机构id
	 */
	public void addUserToOrg(OmUserForm form ,Long orgId){
		if(form != null && orgId != null){
			//保存用户信息
			this.save(form);
			
			//保存用户与机构关联信息
			omUserOrgDao.save(form.getUserId(), orgId);
		}
	}
	
	/**
	 * 建立用户与机构的关联关系
	 * @param userId 用户ID
	 * @param orgId 机构ID
	 */
	public void associateUserToOrg(Long userId, Long orgId){
		omUserOrgDao.save(userId, orgId);
	}
	
	/**
	 * 在机构岗位下新增用户
	 * @param form 用户对象
	 * @param posId 岗位id
	 */
	public void addUserToOrgPos(OmUserForm form, Long posId){
		if(form != null && posId != null){
			//保存用户信息 及 用户岗位关联信息
			this.save(form);
			omUserPositionDao.save(form.getUserId(), posId);
			
			//保存用户与岗位所属机构关联信息
			Long orgId = omPositionService.get(posId).getPartyId();
			omUserOrgDao.save(form.getUserId(), orgId);
		}
	}
	
	/****************分级授权的方法********************/
	
	/**
	 * 判断管理用户是否具有指定用户的管理权限，分管理用户是超级管理员和普通用户2种情况，
	 * 若有权限，返回true；否则，返回false；
	 * @param adminUserId 管理用户主键
	 * @param userId 指定用户主键
	 * @return 
	 */
	@Transactional(readOnly = true)
	public boolean canManageUser(Long adminUserId, Long userId) {
		boolean result = false;
		
		if(adminUserId != null && userId != null){
			
			//超级管理员
			if(this.isSystemAdmin(adminUserId))
				result = true;
			
			//普通用户
			else{
				//查询adminUserId所管理的userIds
				List<Long> userIds =  this.getAdminUsers(adminUserId);
				
				//判断userId是否在userIds中
				result = userIds.contains(adminUserId);
			}
		}
		
		return result;
	}
	
	/**
	 * 根据管理用户查询它可以管理的用户集合，
	 * 包括它可以管理的所有机构的用户集合，以及机构下所有岗位的下级用户的集合
	 */
	@Transactional(readOnly = true)
	private List<Long> getAdminUsers(Long adminUserId){
		List<Long> list = null;
		
		if(adminUserId != null){
			list = new ArrayList<Long>();
			//获得可管理机构
			List<Long> orgIds = omOrgAdminDao.getCanManageOrgIds(adminUserId);
			
			//查询orgIds所关联的用户userIds
			List<Long> userIds = this.getUserIdsByOrgIds(orgIds);
			
			//查询orgIds所关联的岗位posIds
			List<Long> posIds = omPositionService.getPosIdsByOrgIds(orgIds);
			
			//查询岗位posIds关联的所有userIds
			List<Long> pos_userIds = omPositionService.getUserIdsByPosIds(posIds);
			
			list.addAll(userIds);
			list.addAll(pos_userIds);			
		}
		
		return list;
	}

	
	
	/**
	 * 判断管理用户是否具有指定用户数组的全部管理权限，
	 * 若有全部管理权限，返回true；否则，返回false；
	 * @param adminUserId 管理用户主键
	 * @param userIds 指定用户主键或主键数组
	 * @return 
	 */
	@Transactional(readOnly = true)
	public boolean canManageUser(Long adminUserId, Long... userIds) {
		boolean result = false;
		
		if(adminUserId != null && userIds!= null){
			for(Long userId :userIds){
				result = canManageUser(adminUserId, userId);
				if(result == false)
					return result;
			}
		}
		
		return result;
	}
	/**
	 * 根据机构主键列表获取关联用户主键列表
	 * @param orgIds 机构主键列表
	 * @return 用户主键列表
	 */
	@Transactional(readOnly = true)
	private List<Long> getUserIdsByOrgIds(List<Long> orgIds){
		List<Long> userIds = null;
		if(orgIds != null && orgIds.size() != 0){
			String hql = "select distinct ps.userIds from OmOrgAdmin ps where 1=2";
			
			//组装hql
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < orgIds.size(); i++) {
				sb.append(" or orgId="+orgIds.get(i));
			}
			hql = hql+sb.toString();
			
			userIds = this.omUserOrgDao.find(hql);
		}
		return userIds;
	}
	
	
	/**
	 * 如果登陆用户具有指定用户列表的全部权限，则可以进行删除操作，
	 * 否则删除失败
	 * @param adminUserId 登陆用户主键
	 * @param userIds 用户z主键或主键数组
	 * @return 是否成功删除的信息
	 */
	public ResultForm<Object> delete(Long adminUserId, Long... userIds) {
		ResultForm<Object> dto = new ResultForm<Object>(false);
		if(adminUserId != null && userIds != null){
			
			//有权限
			if(this.canManageUser(adminUserId, userIds)){
				this.delete(userIds);
				dto.setSuccess(true);
			}
			
			//没有权限
			else 
				MsgUtils.addNoUserPrivilegeError(dto);
		}
		
		return null;
	}

	
	/**
	 * 关联删除用户，先判断管理用户是否拥有指定用户的管理权限，
	 * 若有，则返回成功删除信息；否则，返回删除失败信息
	 * @param adminUserId 管理用户主键
	 * @param userIds 用户主键或主键数组
	 * @return 是否成功关联删除的信息
	 */
	public ResultForm<Object> deleteUserCascade(Long adminUserId, Long userId) {
		ResultForm<Object> dto = new ResultForm<Object>(false);
		if(adminUserId != null && userId != null){
			
			//有权限
			if(this.canManageUser(adminUserId, userId)){
				this.deleteUserCascade(userId);
				dto.setSuccess(true);
			}
			
			//没有权限
			else
				MsgUtils.addNoUserPrivilegeError(dto);
				
		}
		return dto;
	}

	/**
	 * 若管理用户拥有权限，则根据用户主键获取用户对象，否则返回没有该用户管理权限信息
	 * @param adminUserId 登陆用户主键
	 * @param userIds 用户主键或主键数组
	 * @return 拥有管理权限时，返回查询的用户对象，否则，返回失败的信息
	 */
	@Transactional(readOnly = true)
	public ResultForm<OmUserForm> get(Long adminUserId, Long userId) {
		ResultForm<OmUserForm> dto = new ResultForm<OmUserForm>(false);
		if(adminUserId != null && userId != null){
			
			//有权限
			if(this.canManageUser(adminUserId, userId)){
				dto.setResult(this.get(userId));
				dto.setSuccess(true);
			}
			
			//没有权限
			else
				MsgUtils.addNoUserPrivilegeError(dto);
			
		}
		
		return null;
	}

	
	/**
	 * 根据机构id获取关联用户
	 * @param adminUserId 管理用户主键
	 * @param orgId 机构主键
	 * @return 成功查询的用户form对象列表或者是查询失败的信息
	 */
	@Transactional(readOnly = true)
	public List<OmUserForm> getUsers(Long adminUserId, Long orgId) {
		List<OmUserForm> list = null;
		
		if(adminUserId != null && orgId != null){
			
			//系统管理员
			if(this.isSystemAdmin(adminUserId)){
				list = this.getUsers(orgId);
			}
			
			//普通用户
			else{
				//获取管理用户的授权机构以及其子机构
				List<Long> orgIds = omOrgDao.getCanManageOrgIds(adminUserId);
				
				//过滤掉授权用户的所有父机构的直属用户,只有授权机构以及其子机构的用户才有效
				if(orgIds.contains(orgId))
					list  = this.getUsers(orgId);
			}
		}
		return list;
	}

	/**
	 * 根据岗位主键获取关联用户对象列表；先判断管理用户是否拥有岗位的管理权限；
	 * 若有，则返回用户对象列表和查询成功信息；否则，返回查询失败的信息。
	 * @param adminUserId 管理用户主键
	 * @param posId 机构主键
	 * @return 拥有权限时，返回用户form对象列表；否则，返回查询失败信息
	 */
	@Transactional(readOnly = true)
	public ResultForm<List<OmUserForm>> getUsersByPosId(Long adminUserId, Long posId) {
		ResultForm<List<OmUserForm>> dto =  new ResultForm<List<OmUserForm>>(false);
		if(adminUserId != null && posId != null){
			
			//拥有该岗位的管理权限
			if(omPositionService.canManagePosition(adminUserId, posId)){
				dto.setResult(this.getUsersByPosId(posId));
				dto.setSuccess(true);
			}
			
			else
				MsgUtils.addNoPositionPrivilegeError(dto);
				
		}
		return dto;
	}

	/**
	 * 根据权限保存用户对象列表，若有全部用户的管理权限，则保存，
	 * 否则返回没有管理权限信息
	 * @param adminUserId 管理用户主键
	 * @param forms 用户form对象或对象数组
	 * @return 是否成功保存的信息
	 */
	public ResultForm<Object> save(Long adminUserId, OmUserForm... forms) {
		ResultForm<Object> dto =  new ResultForm<Object>(false);
		if(adminUserId != null && forms != null){
			Long[] userIds = OrgUtils.convertUserFormsToIds(forms);
			
			//有权限
			if(this.canManageUser(adminUserId, userIds)){
				this.save(forms);
				dto.setSuccess(true);
			}
			
			//没有该机构的管理权限
			else
				MsgUtils.addNoUserPrivilegeError(dto);
				
		}
		return null;
	}
	 
	/**
	 * 根据查询面板的查询条件查询机构
	 * @param form 条件查询对象 
	 * @Param page 分页对象
	 * @return 符合条件的分页查询结果
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> searchUser(Long adminUserId, OmUserForm form, Page<OmUserForm> page, Map<String, List<SysCodeForm>> sysCodeBuffer){
		
		//建立分页对象
		Page<OmUser> pg =  PageUtils.newPageInstance(page);
			
		StringBuffer hql = new StringBuffer("from OmUser ps where 1=1 ");
		List values =  new ArrayList();
		
		//获取权限hql条件
		String privCondition  = this.buildGetPrivUserIdsHql(adminUserId);
		if(privCondition != null)
			hql.append(privCondition);
		
		//追加查询条件
		addQueryCondition(hql, values, form);
		
		//排序
		hql.append(HqlUtils.buildOrderBy(page, "ps"));
		
		omUserDao.findPage(pg, hql.toString(), values);

		List<OmUserForm> list = OmUserConverter.convertToFormList(pg.getResult(),
				sysCodeService.getItems(OrgConstant.SYS_CODE_USER_POSITION, sysCodeBuffer),
				sysCodeService.getItems(OrgConstant.SYS_CODE_USER_SEX, sysCodeBuffer));
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	/**
	 * 追加查询条件
	 * @param hql
	 * @param values
	 * @param form
	 */
	private void addQueryCondition(StringBuffer hql, List values, OmUserForm form){
		if(form != null){
			if(form.getLoginName() != null && form.getLoginName().trim().length() > 0){
				hql.append(" and ps.loginName like ?");
				values.add("%"+form.getLoginName()+"%");
			}
			if(form.getUserCode() != null && form.getUserCode().trim().length() > 0){
				hql.append(" and ps.userCode like ?");
				values.add("%"+form.getUserCode()+"%");
			}
			if(form.getUserName() != null && form.getUserName().trim().length() > 0){
				hql.append(" and ps.userName like ?");
				values.add("%"+form.getUserName()+"%");
			}
			if(form.getPosition() != null && form.getPosition().trim().length() > 0){
				hql.append(" and ps.position = ?");
				values.add(form.getPosition());
			}
			if(form.getIsActive() != null && form.getIsActive().trim().length() > 0){
				hql.append(" and ps.isActive = ?");
				values.add(form.getIsActive());
			}
		}
	}
	
	/**
	 * 分页查询全部用户form 对象
	 * @param page 分页对象
	 * @return 分页处理后的全部用户form 对象
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> getAll(Page<OmUserForm> page){
		if(page != null){
			//建立分页对象
			Page<OmUser> pg =  PageUtils.newPageInstance(page);
			
			pg = omUserDao.getAll(pg);
			
			// 转换为Form对象列表并赋值到原分页对象中
			List<OmUserForm> list = OmUserConverter.convertToFormList(pg.getResult());
			PageUtils.copy(pg, list, page);
		}
		return page;
	}
	
	/**
	 * 删除用户关联的功能
	 */
	public void disAssociationFunbyUserId(Long userId){
		if(userId != null){
			String hql = "select ps.ufId from AcUserFunc ps where ps.userId=?";
			List<Long> values =  new ArrayList<Long>();
			values.add(userId);
			List<Long> list = this.userFuncDao.find(hql,values);
			if(list != null && list.size()>0){
				Long[] ufIds = new Long[list.size()];
				ufIds = list.toArray(ufIds);
				this.userFuncDao.delete(ufIds);
			}
		}
	}
	
	/**
	 * 删除跟用户关联的角色
	 */
	public void disAssociationRolebyUserId(Long userId){
		if(userId != null){
			List<Long> list = this.userRoleDao.getDirectRoleIdsByUserId(userId);
			if(list != null && list.size()>0){
				for(Long roleId:list){
					userRoleDao.disAssociateRoleFromUser(roleId, userId);
				}
			}
		}
	}
	
	/**
	 * 删除用户关联的快捷键
	 */
	public void disAssociationShortcutByUserId(Long userId){
		if(userId != null){
			String hql = "select ps.usId from AcUserShortcut ps where ps.userId=?";
			List<Long> values = new ArrayList<Long>();
			values.add(userId);
			List<Long> list = userShortcutDao.find(hql,values);
			if(list != null && list.size()>0){
				Long []usIds = new Long [list.size()];
				usIds = list.toArray(usIds);
				userShortcutDao.delete(usIds);
			}
		}
	}
	
	private void deleteUsers(List<Long> list, Long[] array){
		if(array != null && array.length > 0){
			for(Long e: array){
				if(list!= null && list.size() > 0){
					for(int i = 0; i < list.size(); i++){
						if(e.longValue() == list.get(i).longValue()){
							list.remove(i);
						}
					}
				}
			}
			
		}
	}
	/**
	 * 获取机构下但是不属于指定工作组下的用户（包含它的所有子机构）
	 * @param orgId 机构id
	 * @param groupId 工作组id
	 * @param form 查询条件
	 * @param page 分页条件
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> getUsersInOrgButNotInGroup(Long orgId, Long groupId, OmUserForm form, Page<OmUserForm> page){
		if(orgId != null){
			Page<OmUser> pg =  PageUtils.newPageInstance(page);
			// 获取指定机构的所有子机构ID列表
			List<Long> orgIds = omOrgDao.getAllChildOrgIds(orgId);
			
			//要计算指定机构本身在内
			orgIds.add(orgId);
			//获取机构下的所有用户id
			String hql = "select distinct ps.userId from OmUser ps, OmUserOrg ouo where ps.userId= ouo.userId and " + HqlUtils.buildOrCondition("ouo", "orgId", CollectionUtils.toLongArray(orgIds));
			List<Long> userIdListInOrg = omUserDao.find(hql) ;
			
			Long[] userIdsInGroup = omUserGroupDao.getUserIdsByGroupId(groupId);
			deleteUsers(userIdListInOrg, userIdsInGroup);
			
			return this.getUsersInUserIds(page, form, CollectionUtils.toLongArray(userIdListInOrg));
		}
		return null;
		
	}
	
	/**
	 * 获取机构下不拥有指定岗位的所有用户，包括子机构下的用户
	 * @param orgId 机构id
	 * @param posId 岗位id
	 * @param form 查询参数
	 * @param page 分页参数
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> getUsersNotHavePos(Long orgId, Long posId, OmUserForm form, Page<OmUserForm> page){
		if(orgId != null){
			Page<OmUser> pg =  PageUtils.newPageInstance(page);
			// 获取指定机构的所有子机构ID列表
			List<Long> orgIds = omOrgDao.getAllChildOrgIds(orgId);
			
			//要计算指定机构本身在内
			orgIds.add(orgId);
			//获取机构下的所有用户id
			String hql = "select distinct ps.userId from OmUser ps, OmUserOrg ouo, OmUserPosition oup where ps.userId= ouo.userId  and " + HqlUtils.buildOrCondition("ouo", "orgId", CollectionUtils.toLongArray(orgIds));
			List<Long> userIdListInOrg = omUserDao.find(hql) ;
			
			//获取岗位下的用户
			List<Long> posList = new ArrayList<Long>();
			posList.add(posId);
			List<Long> userIdsHavePos = omPositionService.getUserIdsByPosIds(posList);
			
			//在机构下但是不具备指定岗位的用户
			if(userIdsHavePos != null && userIdsHavePos.size() > 0){
				Long[] userIds = ArrayUtils.calDifference(CollectionUtils.toLongArray(userIdListInOrg), CollectionUtils.toLongArray(userIdsHavePos));
				return this.getUsersInUserIds(page, form, userIds);
			}
			return this.getUsersInUserIds(page, form, CollectionUtils.toLongArray(userIdListInOrg));
		}
		return null;
	}

	/**
	 * 获取不隶属于指定机构的用户列表
	 * @param orgId 指定机构ID
	 * @param form 查询条件
	 * @param page 分页条件
	 */
	@Transactional(readOnly = true)
	public Page<OmUserForm> getUsersNotInOrg(Long orgId, OmUserForm form, Page<OmUserForm> page){
		Page<OmUser> pg =  PageUtils.newPageInstance(page);
		
		// 获取指定机构的所有子机构ID列表
		List<Long> orgIds = omOrgDao.getAllChildOrgIds(orgId);
		
		//要计算指定机构本身在内
		orgIds.add(orgId);
		
		// 隶属于指定机构或其子机构的用户列表查询HQL
		String usersInOrgHql = "select distinct ouo.userId from OmUserOrg ouo where " 
			+ HqlUtils.buildOrCondition("ouo", "orgId", CollectionUtils.toLongArray(orgIds));
		
		StringBuffer hql = new StringBuffer("from OmUser ps where ps.userId not in (");
		hql.append(usersInOrgHql);
		hql.append(")");
		
		List values = new ArrayList();
		
		//追加查询条件
		addQueryCondition(hql, values, form);
		
		//排序
		hql.append(HqlUtils.buildOrderBy(page, "ps"));
		
		omUserDao.findPage(pg, hql.toString(), values);

		PageUtils.copy(pg, OmUserConverter.convertToFormList(pg.getResult()), page);
		return page;
	}
	
	
	/**
	 * 获取指定用户所属机构列表
	 * @param userId
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmUserOrgForm> getRelatedOrgs(Page<OmUserOrgForm> page, Long userId){
		Page pg = PageUtils.newPageInstance(page);
		
		String hql = "select ouo, org.orgName from OmUserOrg ouo, OmOrg org where ouo.orgId=org.orgId and ouo.userId=?";
		List values = new ArrayList();
		values.add(userId);
		omUserOrgDao.findPage(pg, hql, values);
		
		PageUtils.copy(pg, OmUserOrgConverter.convertToForm(pg.getResult()), page);
		return page;
	}
	
	@Transactional(readOnly = true)
	public OmOrgForm getRelatedMainOrg(Long userId){
		String hql = "select org from OmUserOrg ouo, OmOrg org where ouo.orgId=org.orgId and ouo.userId=? order by ouo.isMain desc";
		List<OmOrg> orgs = omUserOrgDao.find(hql, userId);
		OmOrg defaultOrg = (orgs != null && orgs.size() > 0) ? orgs.get(0) : null;
		return OmOrgConverter.convertToForm(defaultOrg);
	}
	
	/**
	 * 获取指定用户所属工作组列表
	 * @param userId
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmUserGroupForm> getRelatedGroups(Page<OmUserGroupForm> page, Long userId){
		Page pg = PageUtils.newPageInstance(page);
		
		String hql = "select oug, gp.groupName from OmUserGroup oug, OmGroup gp where oug.groupId=gp.groupId and oug.userId=?";
		List values = new ArrayList();
		values.add(userId);
		omUserGroupDao.findPage(pg, hql, values);
		
		PageUtils.copy(pg, OmUserGroupConverter.convertToForm(pg.getResult()), page);
		return page;
	}
	
	/**
	 * 获取指定用户所属岗位列表
	 * @param userId
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<OmUserPositionForm> getRelatedPositions(Page<OmUserPositionForm> page, Long userId, String posType){
		Page pg = PageUtils.newPageInstance(page);
		
		String hql = "select oup, pos.posName from OmUserPosition oup, OmPosition pos where oup.posId=pos.posId and oup.userId=? and pos.posType=?";
		omUserPositionDao.findPage(pg, hql, userId, posType);
		
		PageUtils.copy(pg, OmUserPositionConverter.convertToForm(pg.getResult()), page);
		return page;
	}
	
	/**
	 * 根据OmUserOrg对象ID数组作删除
	 * @param uoIds OmUserOrg对象ID数组
	 */
	public void deleteOmUserOrg(Long[] uoIds){
		if(uoIds != null && uoIds.length > 0){
			omUserOrgDao.delete(uoIds);
		}
	}
	
	/**
	 * 根据OmUserGroup对象ID数组作删除
	 * @param ugIds OmUserGroup对象ID数组
	 */
	public void deleteOmUserGroup(Long[] ugIds){
		if(ugIds != null && ugIds.length > 0){
			omUserGroupDao.delete(ugIds);
		}
	}
	
	/**
	 * 根据OmUserPosition对象ID数组作删除
	 * @param upIds OmUserPosition对象ID数组
	 */
	public void deleteOmUserPosition(Long[] upIds){
		if(upIds != null && upIds.length > 0){
			omUserPositionDao.delete(upIds);
		}
	}
	
	/**
	 * 设置主机构
	 * @param userId 用户ID
	 * @param orgId 机构ID
	 */
	public void setMainOrg(Long userId, Long orgId){
		omUserOrgDao.setMainOrg(userId, orgId);
	}
	
	/**
	 * 设置主岗位
	 * @param userId 用户ID
	 * @param posId 岗位ID
	 */
	public void setMainPos(Long userId, Long posId){
		omUserPositionDao.setMainPos(userId, posId);
	}
	
	/**
	 * 构造获取管理用户权限下所有用户的HQL
	 */
	public String buildGetPrivUserIdsHql(Long adminUserId){
		String str = null;
		
		if(adminUserId != null){
			
			//系统管理员
			if(this.isSystemAdmin(adminUserId))
				return null;
			
			//机构管理员
			else{
				
				List<Long> userIds = this.getPrivUserIds(adminUserId);
				if(userIds != null && userIds.size()>0)
					return " and " + HqlUtils.buildOrCondition("ps", "userId", CollectionUtils.toLongArray(userIds));
				else
					return " and 1!=1";
			}
		}
		
		return str;
	}
	
	/**
	 * 获取管理用户权限下的所有用户
	 */
	@Transactional(readOnly = true)
	public List<Long> getPrivUserIds(Long adminUserId){
		if(adminUserId != null){
			
			List<Long> privOrgIds = omOrgDao.getCanManageOrgIds(adminUserId);
			
			if(privOrgIds != null && privOrgIds.size()>0){
				String hql = "select distinct ps.userId from OmUserOrg ps where 1=1 and ";
				hql += HqlUtils.buildOrCondition("ps", "orgId", CollectionUtils.toLongArray(privOrgIds));
				return omOrgAdminDao.find(hql);
			}
		}
		return null;
	}
	
	/**
	 * 获取用户名称
	 * @param loginName 用户登录名
	 * @return
	 */
	@Transactional(readOnly = true)
	public String getUserName(String loginName) {
		OmUserForm user = get(loginName);
		if(user != null)
			return user.getUserName();
		else
			return null;
	}
	
	/**
	 * 根据用户登陆名数组查找用户列表
	 * @param roleCode 角色编号
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<OmUserForm> getUsersLoginNames(String loginNames[]) {
		List<OmUserForm> result = null;
		if(loginNames != null && loginNames.length>0){
			String hql = "";
			StringBuffer sb = new StringBuffer("from OmUser ps where 1=2 ");
			for(String loginName:loginNames)
				sb.append(" or ps.loginName='"+loginName+"'");
			hql = sb.toString();
			List<OmUser> list = this.omUserDao.find(hql);
			result = OmUserConverter.convertToFormList(list);
		}
		return result;
	}
	
	
	/**
	 * 根据岗位主键列表查询关联的用户loginName列表
	 * @param posIds
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<OmUserForm> getUsersByPosIds(List<Long> posIds){
		if(posIds != null && posIds.size() > 0){
			StringBuffer sb = new StringBuffer("select ps from OmUser ps, OmUserPosition up where 1=2 ");
			for(Long posId :posIds)
				sb.append(" or (up.posId=" +posId +" and ps.userId = up.userId)");
			List<OmUser> list = this.omUserDao.find(sb.toString());
			return OmUserConverter.convertToFormList(list);
		}
		return null;
	}
	
	/**
	 * 根据机构主键列表获取关联用户用户名列表
	 * @param orgIds 机构主键列表
	 * @return 用户主键列表
	 */
	@Transactional(readOnly = true)
	public List<OmUserForm> getUsersByOrgIds(List<Long> orgIds){
		if(orgIds != null && orgIds.size() > 0){
			String hql = "select ps from OmUser ps,OmUserOrg uo where 1=2";
			
			//组装hql
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < orgIds.size(); i++) {
				sb.append(" or (uo.orgId="+orgIds.get(i) +" and ps.userId = uo.userId)");
			}
			hql = hql+sb.toString();
			
			List<OmUser> list = this.omUserOrgDao.find(hql);
			return OmUserConverter.convertToFormList(list);
		}
		return null;
	}
	
	/**
	 * 指定用户是否在模糊匹配的集合中
	 * @param userId
	 * @param keyword
	 */
	public boolean isUserLikeKeyword(Long userId,String keyword){
		if(userId != null && keyword != null && keyword.trim().length()>0){
			OmUserForm form = this.get(userId);
			if(form != null ){
				if(form.getUserName().length()>=keyword.length()){
					String subStr = form.getUserName().substring(0, keyword.length());
					if(subStr.equals(keyword))
						return true;
				}
			}
		}
		return false;
	}
	
	
	/**
	 * 根据关键字进行左匹配查询
	 * @param userId
	 * @param keyword
	 * @return
	 */
	public List<OmUserForm> getUserByOrgListAndKeyword(List<OmOrgForm>list,String keyword){
		List<OmUserForm> formList = null;
		if(list != null && list.size()>0 && keyword != null && keyword.trim().length()>0){
			formList = this.omUserDao.getUserByOrgListAndKeyword(list, keyword);
		}
		return formList;
	}
	
	/**
	 * 根据关键字进行左匹配查询
	 * @param userId
	 * @param keyword
	 * @return
	 */
	public List<OmUserForm> getUserByposListAndKeyword(List<OmPositionForm> list,String keyword){
		List<OmUserForm> formList = null;
		if(list != null && list.size()>0 && keyword != null && keyword.trim().length()>0){
			formList = this.omUserDao.getUserByPosListAndKeyword(list, keyword);
		}
		return formList;
	}
	
	//om_user表是否有记录匹配关键字
	public boolean hasUserLikeKeyword(List<OmUserForm>list,String keyword){
		if(keyword != null && keyword.trim().length()>0 && list != null && list.size()>0)
			for(OmUserForm form:list){
				if(this.isUserLikeKeyword(form.getUserId(), keyword))
					return true;
			}
		return false;
	}

	@Override
	public OmUserForm getUserByName(String userName) {
		StringBuffer sb = new StringBuffer("from OmUser where userName='"+userName+"'");
		List<OmUser> list=omUserDao.find(sb.toString());
		if(list.size()>0){
			OmUser user=list.get(0);
			return OmUserConverter.convertToForm(user);
		}
		return null;
	}

	@Override
	public List<OmUserForm> getSelectUsers(Long orgId,String roleIds) {
		List<OmUserForm> result = null;
		if(orgId != null){
			String hql = "select user from OmUser user, OmUserOrg uo,AcUserRole ps where uo.orgId =?" +
					" and uo.userId=user.userId  and ps.userId=user.userId and ps.roleId in ("+roleIds+") order by user.sortNo asc";
			List<OmUser> list = omUserDao.find(hql, orgId);
			result = OmUserConverter.convertToFormList(list);
		}
		return result;
		
	}
}